package com.example.updownload_file.controller;

import com.example.updownload_file.entity.FileInfo;
import com.example.updownload_file.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author tanglp
 * @date 2023/5/26 15:18
 * @description
 */
@Controller
@Slf4j
public class UploadFileController {

    private ModelAndView modelAndView = new ModelAndView("upload");

    @Value("${filePath}")
    private String filePath;

    @Autowired
    private UploadService uploadService;

    @GetMapping("/")
    public String index() {
        return "upload";
    }

    @PostMapping("/upload")
    public ModelAndView upload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {

        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return getAllFileInfos();
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String formatDir = sdf.format(new Date());

            byte[] bytes = file.getBytes();
            File fileDir = new File(filePath + formatDir);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
                fileDir.createNewFile();
            }
            Path path = Paths.get(filePath + formatDir + "/" + file.getOriginalFilename());
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message", "You successfully uploaded '"
                    + file.getOriginalFilename() + "'");

            FileInfo fileInfo = new FileInfo();
            String fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
            fileInfo.setName(fileName);
            String fileExtName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            fileInfo.setType(fileExtName);
            fileInfo.setPath(filePath + formatDir + "/");
            fileInfo.setCreateDate(new Date());

            boolean save = uploadService.save(fileInfo);
            if (save) {
                log.info("持久化成功：" + fileInfo.toString());
            } else {
                log.info("持久化失败！！！");
            }

        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return getAllFileInfos();
    }

    @GetMapping("/download")
    public ResponseEntity<Resource> download(@RequestParam("uploadTime") String uploadTime,
                                             @RequestParam("file") String fileName) throws Exception {

        Resource file = new FileSystemResource(filePath + uploadTime + "/" + fileName);
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName)
                .body(file);
    }

    @GetMapping("/list")
    public ModelAndView getAllFileInfos() {
        List<FileInfo> fileInfos = uploadService.findAll();
        return modelAndView.addObject("fileInfos", fileInfos);
    }

    @GetMapping("/{id}")
    public ModelAndView getFileInfoById(@PathVariable("id") int id) {
        FileInfo fileInfo = uploadService.selectById(id);
        List fileInfos = new ArrayList<FileInfo>();
        fileInfos.add(fileInfo);
        return modelAndView.addObject("fileInfos", fileInfos);
    }


}


